package whf.framework.ext.xml;

import java.util.List;

import org.jdom.Document;
import org.jdom.Element;

import whf.framework.entity.TreeNode;
import whf.framework.exception.AppException;
import whf.framework.ext.tag.TreeStyle;
import whf.framework.log.Log;
import whf.framework.log.LogFactory;
import whf.framework.service.TreeService;

/**
 * @author wanghaifeng
 *
 */
@SuppressWarnings("unchecked")
public class MenuXmlBuilder implements IMenuXmlBuilder{
	private static Log log = LogFactory.getLog(MenuXmlBuilder.class);
	private final static String NODE_NAME = "TreeNode";
	
	private TreeNode root;
	private TreeService finder;
	private TreeStyle menuItemStyle;
	private String action;
	
	public MenuXmlBuilder(TreeNode root, TreeService finder, TreeStyle menuItemStyle, String action){
		this.root = root;
		this.finder = finder;
		this.menuItemStyle = menuItemStyle;
		this.action = action;
	}
	
	private Element buildMenuElement(TreeNode menuItem){
		Element element = new Element(NODE_NAME);
		String text = menuItem.getName();
		String value = String.valueOf(menuItem.getId());
		element.setAttribute("text", text==null?"":text.trim());
		element.setAttribute("value", value==null?"":value.trim());
		if(this.action != null && !"".equals(this.action.trim())){
			String action = this.action+"('"+value+"')";
			element.setAttribute("action", action.trim());
		}
		if(this.menuItemStyle == TreeStyle.CHECKBOX){
			element.setAttribute("checkbox","true");
			element.setAttribute("checked", "false");
		} else if(this.menuItemStyle == TreeStyle.RADIO){
			element.setAttribute("radio", "true");
			element.setAttribute("checked", "false");
		}
		return element;
	}
	
	private void buildMenuElementTree(Element parent, TreeNode menuItem, String queryString) throws AppException{
		List<TreeNode> items = this.finder.findChildren(menuItem, queryString);
		for(TreeNode item: items){
			Element element = this.buildMenuElement(item);
			parent.addContent(element);
			List<TreeNode> children = this.finder.findChildren(item, queryString);
			for(TreeNode child: children){
				this.buildMenuElementTree(element, child, queryString);
			}
		}
	}

	public Document buildXmlDocument(String queryString) {
		Element root = this.buildMenuElement(this.root);
		try{
			this.buildMenuElementTree(root,this.root, queryString);
		}catch(Exception e){
			log.error(this, e);
		}
		return new Document(root);
	}
}
